package com.gltc.util;

import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

public class StringUtil {
	public static final String localhost = "0:0:0:0:0:0:0:1";
	public static final String localhostAddress = "127.0.0.1";
	/**
	 * 浮点行数字格式转换类
	 */
	public static DecimalFormat decimalFormat  = new DecimalFormat("######0.00");   
	/**
	 * 重命名文件
	 * @param path
	 * @param fileName
	 * @return String 文件名称
	 */
	public static String renameFileName(String path, String fileName) {
		File file = new File(path +"/"+ fileName);// 获取要报存的文件路径
		System.out.println(StringUtil.getFileType(fileName));
		if (file.exists()
				&& (StringUtil.getFileType(fileName).equals("jpg")
						|| StringUtil.getFileType(fileName).equals("jpeg")
						|| StringUtil.getFileType(fileName).equals("png") || StringUtil
						.getFileType(fileName).equals("bmp")))// 如果文件已存在就重命名，不存在就直接返回
		{
			return System.currentTimeMillis()+"."+StringUtil.getFileType(fileName) ;
		}
		return fileName;
	}

	/**
	 * 判断字符串是否非空
	 * @param str
	 * @return boolean 是否为空
	 */
	public static boolean isNullOrEmpty(String str) {
		if (null == str || "".equals(str)) {
			return true;
		}
		return false;
	}

	/**
	 * 根据文件名获得文件类型
	 * @param fileName 文件名称
	 * @return String 文件类型
	 */
	public static String getFileType(String fileName) {
		return fileName.substring(fileName.lastIndexOf(".") + 1);
	}
	
	/**
	 * 根据实际文件名获得去掉后缀后的文件名称
	 * @param fileName 文件名称
	 * @return String 去掉后缀后的文件名称
	 */
	public static String getFileName(String s) {
		return s.substring(0, s.lastIndexOf("."));
	}
	
	/**
	 * 校验字符串是否为数字
	 * @param str 字符串
	 * @return boolean 是否为数字
	 */
	public static boolean isNumber(String str){
		boolean flag = false;
		//判断正负数都可以
		//Pattern pattern = Pattern.compile("^[-]{0,1}[0-9]+$");
		Pattern pattern = Pattern.compile("^[1-9][0-9]*$");
		Matcher isNum = pattern.matcher(str);
		if(isNum.matches()){
			flag = true;
		}
		return flag;
	}
	/**
	 * 获取属性文件中的属性值
	 * @param key 属性名
	 * @return String 属性值
	 */
	public static String getPropValue(String key){
		// action配置文件路径  
		@SuppressWarnings("unused")
		String config_path = "WEB-INF/classes/config.properties";  
		// 属性文件   
		Properties prop = new Properties();  
		// 把文件读入文件输入流，存入内存中     
		InputStream fis;
		try {
			//fis = new FileInputStream(new File(path + config_path));
			fis =StringUtil.class.getClassLoader().getResourceAsStream("config.properties");
			//加载文件流的属性     
			prop.load(fis); 
			return prop.getProperty(key);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "";
		}     
	}
	
	/**
	 * 加密算法Md5
	 * @param password 待加密的密码原文
	 * @return String 加密后的字符串
	 * @throws Exception
	 */
	public static String stringToMD5(String password) throws Exception{
		String result="";
		if(null!=password){
		MessageDigest md5 = null;
		StringBuffer hexValue = new StringBuffer();
		try {
			md5 = MessageDigest.getInstance("MD5");
			char[] charArray = password.toCharArray();
			byte[] byteArray = new byte[charArray.length];

			for (int i = 0; i < charArray.length; i++)
				byteArray[i] = (byte) charArray[i];
			byte[] md5Bytes = md5.digest(byteArray);
			for (int i = 0; i < md5Bytes.length; i++) {
				int val = ((int) md5Bytes[i]) & 0xff;
				if (val < 16)
					hexValue.append("0");
				hexValue.append(Integer.toHexString(val));
				result=hexValue.toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}}
		return result;
	}
	
    /**
     * 将字符串转换成List(字符串格式如"12,123,43,1,4")
     * @param  source 被转换的字符串
     * @return List 转换后的结果
     * @throws exception
     */
	public static List<Integer> StringToList(String source) throws Exception{
		List<Integer> result =  null;
		if(null != source && !"".equals(source.trim())){
			String [] target = source.split(",| ");
			result = new ArrayList<Integer>(target.length);
			
			for(int i = 0, len = target.length ; i < len ; i++){
				try{
					Integer tmp = Integer.valueOf(target[i]);
					result.add(tmp);
				}catch(NumberFormatException e){
				   throw new NumberFormatException("字符串转换成整数失败 :\t"+target[i]);	
				}
			}
		}
		
	    return result;
	}
	
	 /**
     * 将字符串转换成List(字符串格式如"12,123,43,1,4")
     * @param  source 被转换的字符串
     * @return List 转换后的结果
     * @throws exception
     */
	public static List<BigDecimal> StringToBigDecimalList(String source) throws Exception{
		List<BigDecimal> result = null;
		if(null != source && !"".equals(source.trim())){
			String [] target = source.split(",| ");
			result = new ArrayList<BigDecimal>(target.length);
			
			for(int i = 0, len = target.length ; i < len ; i++){
				try{
					BigDecimal tmp = new BigDecimal(target[i]);
					result.add(tmp);
				}catch(NumberFormatException e){
				   throw new NumberFormatException("字符串转换成整数失败 :\t"+target[i]);	
				}
			   }
		}
		
	    return result;
	}
	
	/**
	 * 将List<BigDecimal>转换成字符串
	 * @param  source 转换对象
	 * @param  separator 分隔符(为null则默认为",")
	 * @return String 转换结果(用分隔符隔开,如：1,2,3)
	 * @throws Exception
	 */
	public static String BigDecimalListToString(List<BigDecimal> source,String separator){
		StringBuilder buffer = null;
		if(null != source && source.size() > 0){
			buffer = new StringBuilder(source.size());
			if(null == separator){
				separator = ",";
			}
			
			for(int i = 0, len = source.size(); i < len; i++){
				if(i > 0){
					buffer.append(separator + source.get(i).intValue());
				}else{
					buffer.append(source.get(i).intValue());
				}
			}
		}
		
		return (buffer == null ? "" : buffer.toString());
	}
	/**
	 * 将List<String>转换成字符串
	 * @param  source 转换对象
	 * @param  separator 分隔符(为null则默认为",")
	 * @return String 转换结果(用分隔符隔开,如：1,2,3)
	 * @throws Exception
	 */
	public static String StringListToString(List<String> source,String separator){
		StringBuilder buffer = null;
		if(null != source && source.size() > 0){
			buffer = new StringBuilder(source.size());
			if(null == separator){
				separator = ",";
			}
			
			for(int i = 0, len = source.size(); i < len; i++){
				if(i > 0){
					buffer.append(separator + source.get(i));
				}else{
					buffer.append(source.get(i));
				}
			}
		}
		return (buffer == null ? "" : buffer.toString());
	}
	
	/**
     * 将字符串转换成字符List(字符串格式如"12,123,43,1,4")
     * @param  source 被转换的字符串
     * @return List 转换后的结果
     * @throws exception
     */
	public static List<String> StringToStringList(String source) throws Exception{
		
		if(null == source || "".equals(source.trim())){
			throw new IllegalArgumentException("字符串不能为空！");
		}
		
		String [] target = source.split(",| ");
		List<String> result = Arrays.asList(target);
		
	    return result;
	}
	
	/**
	 * 将空字符串转换成null(同时进行左右去空格处理)
	 * @param  target 目标字符串
	 * @return String 转换完成后的字符串
	 */
	public static String blankToNull(String target){
		String result = null;
		  if(null != target && !"".equals(target.trim())){
			  result = target.trim();
		  }
		return result;
	}
	
	/**
	 * 将null字符串转换成空字符串
	 * @param  target 字符串
	 * @return String 转换后的字符串
	 */
	public static String nullToBlank(String target){
		return target == null ? "" : target;
	}
	/**
	 * 将null字符串转换成空字符串
	 * @param  target 字符串
	 * @return String 转换后的字符串
	 */
	public static String nullToBlank(Object target){
		return target == null ? "" : String.valueOf(target).trim();
	}
	/**
	 * 判断是否不为空字符串
	 * @param  target 目标字符串
	 * @return boolean 是否不为空字符串
	 */
	public static boolean isNotBlank(String target){
		if(null != target && !"".equals(target.trim()))
			return true;
		else
			return false;
	}
	/**
	 * 判断数组是否不为空且长度大于0
	 * @param  target 目标数组
	 * @return boolean 是否不为空字符串
	 */
	public static boolean isNotBlank(Object[] target){
		if(null != target && target.length>0)
			return true;
		else
			return false;
	}
	/**
	 * 判断是否不为空字符串
	 * @param  target 目标字符串
	 * @return boolean 是否不为空字符串
	 */
	public static boolean isBlank(String target){
		if(null == target || "".equals(target.trim()))
			return true;
		else
			return false;
	}
	/**
	 * 生成主键
	 * @return String 主键值
	 * @throws Exception 
	 */
	public static String getPrimaryKey() throws Exception {
		String uuid = java.util.UUID.randomUUID().toString();
		uuid = uuid.replaceAll("-", "");
		return uuid;
	}
	
	/**
     * 数字金额大写转换，思想先写个完整的然后将如零拾替换成零
     * 要用到正则表达式
     */
    public static String digitUppercase(double n){
    	try {
    		String fraction[] = {"角", "分"};
            String digit[] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
            String unit[][] = {{"元", "万", "亿"},{"", "拾", "佰", "仟"}};
     
            String head = n < 0? "负": "";
            n = Math.abs(n);
             
            String s = "";
            for (int i = 0; i < fraction.length; i++) {
                s += (digit[(int)(Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i]).replaceAll("(零.)+", "");
            }
            if(s.length()<1){
                s = "整";    
            }
            int integerPart = (int)Math.floor(n);
     
            for (int i = 0; i < unit[0].length && integerPart > 0; i++) {
                String p ="";
                for (int j = 0; j < unit[1].length && n > 0; j++) {
                    p = digit[integerPart%10]+unit[1][j] + p;
                    integerPart = integerPart/10;
                }
                s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i] + s;
            }
            return head + s.replaceAll("(零.)*零元", "元").replaceFirst("(零.)+", "").replaceAll("(零.)+", "零").replaceAll("^整$", "零元整");
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
        
    }
    /**
	 * 根据部门代码获取对应的部门名称
	 * @param departmentCode 部门代码
	 * @return String 部门名称
	 * @throws Exception 
	 */
    public static String getDepartmentName(String departmentCode){
    	String departmentName = null;
    	if(departmentCode != null && !departmentCode.equals("")){
    		try {
    			String str = departmentCode.substring(0, 6);
    			if(str.equals("411400") || str.equals("411401") || str.equals("411402") 
    					|| str.equals("411403") || str.equals("411498") || str.equals("411497") ){
    				departmentName = "河南省商丘市交警支队";
    			}else if(str.equals("411499")){
    				departmentName = "河南省商丘市高速大队";
    			}else if(str.equals("411425")){
    				departmentName = "河南省虞城县交警大队";
    			}else if(str.equals("411426")){
    				departmentName = "河南省夏邑县交警大队";
    			}else if(str.equals("411423")){
    				departmentName = "河南省宁陵县交警大队";
    			}else if(str.equals("411422")){
    				departmentName = "河南省睢县交警大队";
    			}else if(str.equals("411421")){
    				departmentName = "河南省民权县交警大队";
    			}else if(str.equals("411424")){
    				departmentName = "河南省柘城县交警大队";
    			}else 
    				departmentName = "";
    			System.out.println("机关代码："+str+"，发票处理机关："+departmentName);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    	return departmentName;
	}
	public static void main(String[] args) throws Exception {
		List<String>  aaa = new ArrayList<String>();
		aaa.add("fff");
		aaa.add("eeeee");
		System.out.println(String.valueOf(aaa));
		//BigDecimal d = new BigDecimal("12.5");
		//System.out.println(d.toBigInteger());
		System.out.println(stringToMD5("111111"));
	}
	
	/**
	 * 将空字符串转换成null(同时进行左右去空格处理)
	 * @param  target 目标字符串
	 * @return String 转换完成后的字符串
	 */
	public static String BlankToNull(String target){
		String result = null;
		  if(null != target && !"".equals(target.trim())){
			  result = target.trim();
		  }
		return result;
	}
	/**
	 * 获取IP地址
	 * @param request http请求对象
	 * @return String IP地址
	 * @throws Exception
	 */
	public static String getRemoteIPAddress(HttpServletRequest request) {
       String ip = request.getHeader("x-forwarded-for");
       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
           ip = request.getHeader("Proxy-Client-IP");
       }
       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
           ip = request.getHeader("WL-Proxy-Client-IP");
       }
       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    	   ip = request.getRemoteAddr();
       }
       if(ip.equals(localhost)) return localhostAddress;
       return ip;
	}
	
	  /**
     * 生成主键
     * @return String 主键值
     * @throws Exception 
     */
    public static String createPK() throws Exception {
    	String uuid = UUID.randomUUID().toString();
    	uuid = uuid.replaceAll("-", "");
    	return uuid;
    }
}
